
package cz.czu.pef.DataModelling;

import java.util.*;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Index;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cz.czu.pef.DataModelling.utils.Lazy;

@Entity
@Table(name = "MEDICAL_EXAMINATIONS")
@ManagedBean
@ViewScoped
@Component
public class MedicalExamination extends IdPersistenceObject
{
	private static final long serialVersionUID = -4318181001409286326L;
	
	@Column(nullable=false)
	@Index(name="IDX_MEDEXAM_LAST_PASS")
	private Date lastPass;

	@ManyToOne(fetch = FetchType.EAGER, targetEntity=MedicalExaminationType.class, optional=false, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
	private MedicalExaminationType medicalExaminationType;

	@ManyToMany(fetch = FetchType.LAZY, targetEntity = Employee.class, mappedBy = "medicalExaminations", cascade=CascadeType.ALL) // all cascades!
	private Set<Employee> employees;

	public MedicalExamination()
	{
	}
	
	@Lazy
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	public Set<Employee> getEmployees()
	{
		return employees;
	}
	
	@Lazy
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	public MedicalExaminationType getMedicalExaminationType()
	{
		return medicalExaminationType;
	}

	public void setMedicalExaminationType(MedicalExaminationType medicalExaminationType)
	{
		this.medicalExaminationType = medicalExaminationType;
	}


	public Date getExpiration()
	{
		// TODO: Compute expiration here from Employee => Roles => RoleType => 
		return null;
	}
	
	public Date getLastPass()
	{
		return lastPass;
	}

	
	public void setLastPass(Date lastPass)
	{
		this.lastPass = lastPass;
	}

	@Lazy
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	@Override
	public String toString()
	{
		StringBuilder builder = new StringBuilder();
		builder.append("MedicalExamination [lastPass=");
		builder.append(lastPass);
		builder.append(", medicalExaminationType=");
		builder.append(medicalExaminationType);
		builder.append(", toString()=");
		builder.append(super.toString());
		builder.append("]");
		return builder.toString();
	}
	
	/**
	 * Can be deleted (in cascade).
	 */
	@Override
	public boolean canBeRemoved()
	{
		return true;
	}
}